<?php
/**
 * @package pmapi
 * @copyright Copyright (c)2014 Enrico Fagnoni
 * @license GNU General Public License version 3, or later
 *
 * @since 1.0.0
 */
 
defined('_JEXEC') or die;

if (!class_exists('VirtueMartModelUser')) require ( JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'user.php');

class PmapiModelUser extends VirtueMartModelUser 
{
    public function setId($id)
    {
        if($this->_id!=$id){
            $this->_id = (int)$id;
            $this->_data = null;
            $this->customer_number = 0;
        }
    }


    protected function _isVisible($u)
    {
        $userId = JFactory::getUser()->id;
        if (!$u->virtuemart_user_id) {
            // case 1: anonymous user
            $result = true;
        } elseif ($u->virtuemart_user_id == $userId) {
            // case 2: current user can always display him/her self
            $result = true;
        } elseif($u->user_is_vendor){
            // case 3: current user can always display a vendor
            $result = true;
        } else {
            // case 4: if current user is a shop admin or an admin...
            if (!class_exists('Permissions')) require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'permissions.php');
            $perms = Permissions::getInstance();
            $perms->getPermissions(); // loads current user permission
            
            if ($perms->isSuperVendor()) {
                // case 3.1 an admin always can show users
                $result = true;   
            } elseif ($perms->check('storeadmin')) {
                // case 3.2 a shopandmin can visualize  users of the administered shop
                //get additional info about current user
                $vendorId = $db
                    ->setQuery( 
                        $db->getQuery(true)            
                            ->select('virtuemart_vendor_id')
                            ->from( '#__virtuemart_vmusers' )
                            ->where( "virtuemart_user_id = $userId")
                      )
                    ->loadResult();
                $result = ($vendorId && $u->virtuemart_vendor_id==$vendorId);              
            } else {
                $result = false;
            }
        }
        
        return $result;
    }    
    
    
    private function getCountryName($id)
    {
        static $_countries = array();
        
        if( !isset($_countries[$id])){
            $model = $this->getModel('country');
            $model->setId($id);
            $country = $model->getData($id);
            $_countries[$id] = $country?$country->country_name:'';
        }

        return $_countries[$id]; 
    }
    
    
    private function getStateName($id)
    {
        static $_states = array();
        
        if( !isset($_states[$id])){
            $model = $this->getModel('state');
            $model->setId($id);
            $state = $model->getSingleState();
            $_states[$id] = $state?$state->state_name:'';
        }
        
        return $_states[$id]; 
    }
      
    
    public function getItem()
    {                         
        $id = JFactory::getApplication()->input->get('id',null);
        $this->setId($id);
        $u = $this->getUser();

        // Check for errors.
        if (count($errors = $this->get('Errors')) || ($u->virtuemart_user_id!=$id)) {
            throw new Exception(implode("\n", $errors)||'Not Found', 404);
        }
        if (!$this->_isVisible($u)){
            throw new Exception('Unauthorized', 401);
        }
        
        // Inject additional data to user
        foreach ($u->userInfo as $info ){
            $info->country = $this->getCountryName($info->virtuemart_country_id);
            $info->state = $this->getStateName($info->virtuemart_state_id);
        }  
        return $u;
    }
}
